import { hasLicense} from '@/api/chain';
import { setExpire, getExpire} from '@/utils/index';
import store from '@/store/index.d';
import axios from 'axios'
function randomString(expect) {
  let e = expect || 32,
    t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
    a = t.length,
    n = "";
  for (let i = 0; i < e; i++) {
    n += t.charAt(Math.floor(Math.random() * a))
  }
  return n
}
// 获取token
export const getToken = (sfn,efn) => {
  let accessToken = getExpire('access_token');
  if (accessToken) {
    getTicket(accessToken,sfn)
  } else {
    axios.get(store.getters.gatewayUrl + '/ebus/wwlapi/cgi-bin/gettoken?corpid=' +
      store.getters.corpId + '&corpsecret=' + store.getters.secret)
      .then(res => {
        if (res.data.access_token) {
          setExpire('access_token', res.data.access_token, res.data.expires_in * 1000);
          getTicket(res.data.access_token,sfn);
        }else{
          efn(res);
        }
      });
  }
}
//获取ticket
export const getTicket = (accessToken,sfn) => {
  let ticket = getExpire('ticket');
  if (ticket) {
    setWxConfig(ticket,sfn);
  } else {
    axios.get(store.getters.gatewayUrl + '/ebus/wwlapi/cgi-bin/get_jsapi_ticket?access_token=' + accessToken)
      .then(res => {
        setExpire('ticket', res.data.ticket, res.data.expires_in * 1000);
        setWxConfig(res.data.ticket,sfn);
      });
  }
}
//配置微信
export const setWxConfig = (ticket,sfn) => {
  let timestamp = Date.parse(new Date()).toString().substr(0, 10);
  let noncestr = randomString(16);
  let Hashes = require('jshashes');
  let SHA1 = new Hashes.SHA1;
  let str1 = 'jsapi_ticket=' + ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + window.location.origin + window.location.pathname;
  let sign = SHA1.hex(str1);
  wx.config({
    beta: true,// 调用wx.invoke形式的接口值时，该值必须为true。
    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的 参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId: store.getters.corpId, // 必填，粤政易的cropID
    timestamp: timestamp, // 必填，生成签名的时间戳
    nonceStr: noncestr, // 必填，生成签名的随机串
    signature: sign,// 必填，签名，见附录1
    jsApiList: ['scanQRCode'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
  });
  sfn && sfn();
}
